import axios from "axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import Cookies from "js-cookie";
interface RequestConfig extends AxiosRequestConfig {
  url: string;
  method?: string;
  data?: any;
  params?: any;
  headers?: any;
  timeout?: number;
  withCredentials?: boolean;
  message?: string;
}

export const baseApiUrl = import.meta.env.VITE_BASE_API_URL;

const service = axios.create({
  baseURL: baseApiUrl,
  timeout: 10000,
  withCredentials: true, //允许携带cookie
});

service.interceptors.request.use(
  (config) => {
    const token = Cookies.get("token");
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);

service.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  },
);

export const request = async (req: RequestConfig) => {
  try {
    const data = await service.request(req);
    console.log(data, "data");
    return data.data;
  } catch (error: any) {
    return Promise.reject(error);
  }
};
